/**
 * 消息页
 */
import React, { PureComponent } from "react";
import {
  Image,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
  TextInput,
  FlatList,
  TouchableWithoutFeedback
} from "react-native";
import actions from "../../models/actions";
import NavigationBar from "../../components/navigationBar";
import { connect } from "react-redux";
import {
  LoginToken,
  safeAreaBottomHeight,
  screenWidth,
  statusBarHeight
} from "../../util/AdapterUtil";
// let Code_Push_Key = "Y0yM5lrPkEKUGjJvhaPQX6pwRUv74ksvOXqog"
import * as requestApi from "../../util/requestApi";

class EnterpriseInfoScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      userId: "", //用户id
      updaterSource: 1, //更新人来源 1汽修商 2汽配商 3平台
      companyId: 0,
      companyType: 1,
      companyName: "",
      province: "请选择", // {id: 1, provinceId: "110000", provinceName: "北京市"}
      provinceId: "",
      city: "请选择",
      cityId: "",
      county: "请选择",
      countyId: "",
      address: "",
      phone: "",
      provincedata: [],
      citydata: [],
      countydata: [],
      showSearchpcc: false, //是否显示选择框
      index: 0, //当前 是0省 1市  2县
      isEditable: true //是否可以编辑
    };
  }

  componentDidMount() {
    this.getEnterpriseInfo();
    if (this.props.userInfo.uperUserId) {
      // alert(this.props.userInfo.uperUserId);
      this.setState({
        isEditable: false
      });
    }
  }

  render() {
    // const userInfo = this.props.token? this.props.token : this.props.userInfo;
    // const isChildAccount =  !!userInfo.uperUserId;
    const isEditable = this.state.isEditable;
    return (
      <TouchableWithoutFeedback
        onPress={() => {
          this.setState({
            showSearchpcc: false
          });
        }}
      >
        <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
          <NavigationBar
            navigation={this.props.navigation}
            isBack={true}
            title={"企业信息"}
          />
          <ScrollView
            showsVerticalScrollIndicator={false}
            style={{
              width: "100%",
              backgroundColor: "#F9F9F9"
            }}
          >
            <View style={{ height: 10, backgroundColor: "#F9F9F9" }} />

            <View style={styles.itemStyle}>
              <Text style={{ color: "#606060", fontSize: 18 }}>身份类型</Text>

              <View
                style={{
                  padding: 0,
                  textAlign: "right",
                  flex: 1,
                  height: 40,
                  alignItems: "flex-end",
                  justifyContent: "center"
                }}
              >
                <Text style={{ color: "#777777", fontSize: 16 }}>
                  {this.state.companyType === 1 ? "汽修商" : "汽配商"}
                </Text>
              </View>
            </View>
            <View style={styles.divider} />
            <View style={styles.itemStyle}>
              <Text style={{ color: "#606060", fontSize: 18 }}>企业名称</Text>

              <TextInput
                style={{
                  padding: 0,
                  textAlign: "right",
                  color: "#777777",
                  fontSize: 16,
                  flex: 1,
                  height: 40,
                  alignItems: "center",
                  justifyContent: "center"
                }}
                autoFocus={false}
                maxLength={18}
                editable={this.state.isEditable}
                onChangeText={text => {
                  if (text != null && text.length >= 18) {
                    Toast.show("名称不能超过18个字符", 1000);
                  } else {
                    this.setState({
                      companyName: text
                    });
                  }
                }}
                onSubmitEditing={() => {}}
              >
                {this.state.companyName}
              </TextInput>
            </View>
            <View style={styles.divider} />
            <View style={styles.itemStyle}>
              <Text style={{ color: "#606060", fontSize: 18, width: 40 }}>
                区域
              </Text>
              <View
                style={{
                  flex: 1,
                  justifyContent: "flex-end",
                  flexDirection: "row"
                }}
              >
                <TouchableOpacity
                  style={{
                    padding: 0,
                    textAlign: "right",
                    flex: 1,
                    height: 40,
                    alignItems: "flex-end",
                    justifyContent: "center"
                  }}
                  disabled={!this.state.isEditable}
                  onPress={() => {
                    requestApi
                      .getProvince()
                      .then(res => {
                        this.setState({
                          provincedata: res,
                          showSearchpcc: !this.state.showSearchpcc,
                          index: 2
                        });
                      })
                      .catch(err => {
                        Toast.show(err.msg, 1000);
                      });
                  }}
                >
                  <Text
                    style={{ color: "#777777", fontSize: 14 }}
                    numberOfLines={1}
                  >
                    {this.state.province}
                  </Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={{
                    marginLeft: 10,
                    padding: 0,
                    textAlign: "right",
                    flex: 1,
                    height: 40,
                    alignItems: "flex-end",
                    justifyContent: "center"
                  }}
                  disabled={!this.state.isEditable}
                  onPress={() => {
                    let params = { parentId: this.state.provinceId };
                    requestApi
                      .getCity(params)
                      .then(res => {
                        this.setState({
                          citydata: res,
                          showSearchpcc: !this.state.showSearchpcc,
                          index: 1
                        });
                      })
                      .catch(err => {
                        Toast.show(err.msg, 1000);
                      });
                  }}
                >
                  <Text
                    style={{ color: "#777777", fontSize: 14 }}
                    numberOfLines={1}
                  >
                    {this.state.city}
                  </Text>
                </TouchableOpacity>

                <TouchableOpacity
                  style={{
                    marginLeft: 10,
                    padding: 0,
                    textAlign: "right",
                    flex: 1,
                    height: 40,
                    alignItems: "flex-end",
                    justifyContent: "center"
                  }}
                  disabled={!this.state.isEditable}
                  onPress={() => {
                    let params = { parentId: this.state.cityId };
                    requestApi
                      .getCountry(params)
                      .then(res => {
                        this.setState({
                          countydata: res,
                          showSearchpcc: !this.state.showSearchpcc,
                          index: 0
                        });
                      })
                      .catch(err => {
                        Toast.show(err.msg, 1000);
                      });
                  }}
                >
                  <Text
                    style={{ color: "#777777", fontSize: 14 }}
                    numberOfLines={1}
                  >
                    {this.state.county}
                  </Text>
                </TouchableOpacity>
              </View>
            </View>
            {/*省市县*/}
            {this.state.showSearchpcc ? this.showSearchpccView() : null}

            <View style={styles.divider} />
            <View style={styles.itemStyle}>
              <Text style={{ color: "#606060", fontSize: 18 }}>地址</Text>

              <TextInput
                style={{
                  padding: 0,
                  textAlign: "right",
                  color: "#777777",
                  fontSize: 16,
                  flex: 1,
                  height: 40,
                  alignItems: "center",
                  justifyContent: "center"
                }}
                autoFocus={false}
                maxLength={25}
                editable={this.state.isEditable}
                onChangeText={text => {
                  if (text != null && text.length >= 25) {
                    Toast.show("地址不能超过25个字符", 1000);
                  } else {
                    this.setState({
                      address: text
                    });
                  }
                }}
                onSubmitEditing={() => {}}
              >
                {this.state.address}
              </TextInput>
            </View>
            <View style={styles.divider} />
            <View style={styles.itemStyle}>
              <Text style={{ color: "#606060", fontSize: 18 }}>电话</Text>

              <TextInput
                style={{
                  padding: 0,
                  textAlign: "right",
                  color: "#777777",
                  fontSize: 16,
                  flex: 1,
                  height: 40,
                  alignItems: "center",
                  justifyContent: "center"
                }}
                autoFocus={false}
                keyboardType={"numeric"}
                maxLength={11}
                editable={this.state.isEditable}
                onChangeText={text => {
                  this.setState({
                    phone: text
                  });
                }}
                onSubmitEditing={() => {}}
              >
                {this.state.phone}
              </TextInput>
            </View>

            {isEditable && (
              <TouchableOpacity
                style={{
                  marginTop: 30,
                  marginLeft: 15,
                  marginRight: 15,
                  height: 45,
                  borderRadius: 6,
                  backgroundColor: "#4A90E2",
                  justifyContent: "center",
                  alignItems: "center"
                }}
                onPress={this.upEnterpriseInfo.bind(this)}
              >
                <Text style={{ color: "#fff", fontSize: 14 }}>保存更新</Text>
              </TouchableOpacity>
            )}
          </ScrollView>
          <View style={{ height: safeAreaBottomHeight }} />
        </View>
      </TouchableWithoutFeedback>
    );
  }

  showSearchpccView() {
    return (
      <View
        style={{
          zIndex: 99,
          position: "absolute",
          top: 120 + statusBarHeight + 50,
          right: ((screenWidth - 55) * this.state.index) / 3 + 5,
          width: 80,
          maxHeight: 180,
          backgroundColor: "#fff",
          borderRadius: 4,
          borderWidth: 1,
          borderColor: "#ccc"
        }}
      >
        <ScrollView>
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={
              this.state.index === 0
                ? this.state.countydata
                : this.state.index === 1
                ? this.state.citydata
                : this.state.provincedata
            }
            horizontal={false}
            keyExtractor={(item, index) => index.toString()}
            renderItem={this._renderItem}
          />
        </ScrollView>
      </View>
    );
  }

  _renderItem = ({ item }) => (
    <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = id => {
    if (this.state.index === 0) {
      const cIndex = this.state.countydata.findIndex(
        item => item.countyId === id
      );
      let a = this.state.countydata[cIndex];
      this.setState({
        county: a.countyName,
        countyId: a.countyId,
        showSearchpcc: false
      });
    } else if (this.state.index === 1) {
      /*cityId: "110100"
                cityName: "市辖区"*/
      const cityIndex = this.state.citydata.findIndex(
        item => item.cityId === id
      );
      let b = this.state.citydata[cityIndex];

      if (this.state.cityId === b.cityId) {
        return;
      } else {
        this.setState({
          city: b.cityName,
          cityId: b.cityId,
          showSearchpcc: false,
          county: "请选择",
          countyId: ""
        });
      }
    } else if (this.state.index === 2) {
      const prevIndex = this.state.provincedata.findIndex(
        item => item.provinceId === id
      );
      let c = this.state.provincedata[prevIndex];
      if (this.state.provinceId === c.provinceId) {
        return;
      } else {
        this.setState({
          province: c.provinceName,
          provinceId: c.provinceId,
          showSearchpcc: false,
          city: "请选择",
          cityId: "",
          county: "请选择",
          countyId: ""
        });
      }
    }
  };

  //获取企业信息
  getEnterpriseInfo() {
    let { companyId } = this.state;
    let params = { companyId };
    requestApi
      .getEnterpriseInformation(params)
      .then(res => {
        this.setState({
          companyId: res.companyId,
          companyType: res.companyType,
          companyName: res.companyName,
          province: res.provinceName ? res.provinceName : "请选择",
          provinceId: res.province,
          city: res.cityName ? res.cityName : "请选择",
          cityId: res.city,
          county: res.countyName ? res.countyName : "请选择",
          countyId: res.county,
          address: res.address,
          phone: res.phone
        });
      })
      .catch(err => {
        Toast.show(err.msg, 1000);
      });
  }

  //更新企业信息
  upEnterpriseInfo() {
    //
    let {
      companyType,
      companyName,
      provinceId,
      cityId,
      countyId,
      address,
      phone
    } = this.state;
    if (
      typeof provinceId == "undefined" ||
      provinceId == null ||
      provinceId == ""
    ) {
      Toast.show("请输入区域", 1000);
      return;
    }
    if (typeof cityId == "undefined" || cityId == null || cityId == "") {
      Toast.show("请输入区域", 1000);
      return;
    }
    if (typeof countyId == "undefined" || countyId == null || countyId == "") {
      Toast.show("请输入区域", 1000);
      return;
    }
    let params = {
      companyType: companyType,
      companyName: companyName,
      province: provinceId,
      city: cityId,
      county: countyId,
      address: address,
      phone: phone
    };
    requestApi
      .upEnterpriseInformation(params)
      .then(res => {
        Toast.show("修改成功", 1000);
      })
      .catch(err => {
        Toast.show(err.msg, 1000);
      });
  }
}

const styles = StyleSheet.create({
  itemStyle: {
    paddingLeft: 15,
    paddingRight: 15,
    height: 60,
    flexDirection: "row",
    backgroundColor: "#fff",
    alignItems: "center"
  },
  divider: {
    marginLeft: 70,
    height: 1,
    backgroundColor: "#F9F9F9",
    transform: [{ scaleY: 0.5 }]
  }
});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {}
)(EnterpriseInfoScreen);

/*{
	"companyId": 0,
	"companyType": 1,
	"companyName": "辛巴",
	"province": "140000",
	"city": "140100",
	"county": "140106",
	"address": "成都市",
	"phone": "1331234567"
}*/

class MyListItem extends PureComponent {
  _onPress = () => {
    this.props.onPressItem(
      this.props.item.provinceId
        ? this.props.item.provinceId
        : this.props.item.cityId
        ? this.props.item.cityId
        : this.props.item.countyId
        ? this.props.item.countyId
        : ""
    );
  };

  render() {
    return (
      <View style={{ height: 40 }}>
        <TouchableOpacity
          style={{
            flexDirection: "row",
            height: 30,
            marginLeft: 5,
            marginTop: 5,
            marginRight: 5,
            marginBottom: 5,
            alignItems: "center",
            justifyContent: "center"
          }}
          onPress={this._onPress.bind(this)}
        >
          <Text style={{ color: "#222", fontSize: 12 }}>
            {this.props.item.provinceName
              ? this.props.item.provinceName
              : this.props.item.cityName
              ? this.props.item.cityName
              : this.props.item.countyName
              ? this.props.item.countyName
              : ""}
          </Text>
        </TouchableOpacity>
        <View
          style={{
            height: 1,
            backgroundColor: "#DDDDDD",
            transform: [{ scaleY: 0.5 }]
          }}
        />
      </View>
    );
  }
}
